/**
 * Copyright 2012 Wurlf Web Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wurflws;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.wurfl.core.Device;
import net.sourceforge.wurfl.core.WURFLHolder;

import org.json.JSONException;
import org.json.JSONObject;

@SuppressWarnings("serial")
public class WurflServlet extends HttpServlet{

	private static final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
	/**
	 * Please use a proper cache provider like memcached.
	 * This is just for demonstration purpose
	 */
	private static final Map<String, JSONObject> cache = new HashMap<String, JSONObject>();
	
	/**
	 * Set Cache Expiration
	 * @param response http response object
	 * @param minutes cache expiration value
	 */
	
	static public void setExpire(HttpServletResponse response, int minutes){
    	Calendar c = Calendar.getInstance();
    	c.add(Calendar.MINUTE, minutes);
    	response.setHeader("Expires", format.format(c.getTime()));
	}
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		String userAgent = request.getParameter("ua");
		if (userAgent == null){
			// ua parameter not set, we'll use the user agent header
			userAgent = request.getHeader("User-Agent");
		}
		
		if (userAgent == null || userAgent.length() == 0){
			log("User Agent invalid");
			return;
		}
		String search = request.getParameter("search");
		// get from cache
		JSONObject object = getCacheEntry(userAgent);
		if (object == null){
			WURFLHolder wurflHolder = (WURFLHolder) getServletContext().getAttribute("net.sourceforge.wurfl.core.WURFLHolder");
			Device device = wurflHolder.getWURFLManager().getDeviceForRequest(userAgent);
			if (device != null) {
				object = new JSONObject(device.getCapabilities());
				updateCacheEntry(userAgent, object);
			}else{
				object = new JSONObject();
			}
		}
		try{
			object = getCapabilities(object, search);			
			String result = object.toString(1);
			setExpire(response, 120);
			response.getOutputStream().write(result.getBytes("UTF-8"));
		}catch (Exception e) {
			log("JSON ERROR", e);
		}
	}
	
	/**
	 * Extract capabilities.<br/>If capabilities filter is set only the specified capabilities are returned
	 * @param object JSON object containing capabilities of device
	 * @param search capabilities filter (Ex: is_wireless_device|brand_name|model_name|resolution_width|resolution_height|full_flash_support|flash_lite_version|mobile_browser|device_os|ajax_xhr_type|ajax_support_javascript)
	 * @return json object containing the device capabilities
	 * @throws JSONException
	 */
	
	private JSONObject getCapabilities(final JSONObject object, String search) throws JSONException{
		if (search != null && search.length() > 0){
			// extract capabilities
			String [] capabilities = search.split("\\|");
			if (capabilities != null && capabilities.length > 0){
				JSONObject filter = new JSONObject();
				// loop through each capability
				for (String cap : capabilities){
					if (cap == null || cap.length() <= 0){
						// invalid
						continue;
					}
					// extract value
					Object value = object.opt(cap.trim());
					if (value != null){
						filter.put(cap, value);
					}
				}
				if (filter.length() > 0){
					return filter;
				}
			}
		}
		return object;
	}
	
	private JSONObject getCacheEntry(final String ua){
		return cache.get(ua);
	}
	
	private void updateCacheEntry(final String ua, final JSONObject result){
		if (cache != null) cache.put(ua, result);
	}
}
